import java.util.*;

public class IsWordYiWei {
    /**
     * 判断两个单词是否异位
     * 思路：首先判断两个字符串长度是否相等，其次由于两单词在排序后相等，所以比较排序后的两单词
     * @param s
     * @param t
     */
    public boolean isAnagram(String s,String t){
        char[] charsS = s.toCharArray();
        char[] charsT = t.toCharArray();
        if(charsS.length!=charsT.length){return false;}
        Arrays.sort(charsS);
        Arrays.sort(charsT);
//        System.out.println(Arrays.toString(charsS)+"**"+Arrays.toString(charsT));
        return String.valueOf(charsS).equals(String.valueOf(charsT));
    }

    public static void main(String[] args) {
        System.out.println(new IsWordYiWei().isAnagram("anagram", "nagaram"));
    }
}

/**
 * 给定一个字符串数组，将字母异位词组合在一起。字母异位词指字母相同，但排列不同的字符串。
 */
class SortWordYiWei{

    public List<List<String>> groupAnagrams(String[] strs) {
        if(strs.length==0){
            return new ArrayList();
        }
        Map<String,List> map = new HashMap<String,List>();
        List<List<String>> list = new ArrayList<>();
        List<String> keyNames = new ArrayList<>();
        for (String str : strs) {
            char[] chars = str.toCharArray();
            Arrays.sort(chars);
            String key = String.valueOf(chars);
            if(!map.containsKey(key)){
                map.put(key,new ArrayList());
                keyNames.add(key);
            }
            map.get(key).add(str);
        }
        for (String keyName : keyNames) {
            list.add(map.get(keyName));
        }
        

        return list;
    }

    public static void main(String[] args) {
        List<List<String>> listList = new SortWordYiWei().groupAnagrams(new String[]{"eat", "tea", "tan", "ate", "nat", "bat"});
        for (List<String> strings : listList) {
            for (String string : strings) {
                System.out.println(string);
            }
        }
    }
}
